package com.l.im.server;

import com.l.im.common.config.ConfigReader;
import com.l.im.service.init.WebSocketChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;


/**
 * @program: LIM
 * @description: server
 * @author: Alex Wu
 * @createDate: 2025-04-14 16:13
 **/

@Slf4j
public class IMServer {
    private final int port;

    public IMServer() {
        this.port = ConfigReader.getInstance().getOrDefault("server.port", Integer.class, 8090);
    }

    public void start() throws InterruptedException{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebSocketChannelInitializer());

            Channel channel = serverBootstrap.bind(port).sync().channel();
            log.info("server started at port: " + port);
            channel.closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
